<!-- eslint-disable vue/no-parsing-error -->
<template>
  <div>
    <el-container style="flex-wrap: wrap;">
      <!-- 头部导航栏 -->
      <BreadHeader></BreadHeader>
      <XPannel>
        <!-- 插槽--头部 -->
        <template v-slot:header>
          <!-- <div slot="header" class="clearfix"> -->
          <span>用户管理</span>
          <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
          <!-- 导出excelJs文件 -->
          <el-button
            type="primary"
            style="float: right; padding: 10px 20px; margin-left: 15px"
            @click="adduser"
            >添加人员</el-button
          >
          <el-button
            @click="download()"
            type="info"
            style="float: right; padding: 10px 15px"
            >导出Excel</el-button
          >
          <!-- </div> -->
        </template>
        <!-- 插槽--主体内容 -->
        <template v-slot:default>
          <div>
            <!-- 搜索功能----- -->
            <el-row style="margin: 5px 0">
              <el-col :span="1.8" style="padding: 0 0">
                <template>
                  <p style="color: #303133; font-size: 16px; line-height: 40px">
                    搜索栏：
                  </p>
                </template>
              </el-col>
              <el-col :span="5" style="padding: 0 0">
                <el-input
                  placeholder="请输入手机号(账号)"
                  v-model="seachermobile"
                  clearable
                >
                </el-input>
              </el-col>
              <el-col :span="5" style="padding: 0 0; margin: 0 10px">
                <el-input
                  placeholder="请输入姓名"
                  v-model="seacheruname"
                  clearable
                >
                </el-input>
              </el-col>
              <el-col :span="5" style="padding: 0 0">
                <template>
                  <el-select
                    v-model="searchvalue"
                    placeholder="请选择部门"
                    style="width: 100%"
                    clearable
                  >
                    <el-option label="宿管" value="1"></el-option>
                    <el-option label="总务" value="2"></el-option>
                    <el-option label="维修师傅" value="3"></el-option>
                    <el-option label="老师" value="4"></el-option>
                    <el-option label="学生" value="5"></el-option>
                  </el-select>
                </template>
              </el-col>
              <el-col :span="2" style="margin-left: 15px">
                <el-button
                  type="primary"
                  @click="searchusers"
                  style="padding: 12px 15px"
                >
                  <i class="el-icon-search"></i>搜索
                </el-button>
              </el-col>
            </el-row>
            <!-- 添加人员的抽屉 -->
            <el-drawer
              title="添加人员"
              :visible.sync="draweradd"
              ref="drawer_add"
              :show-close="true"
              style="text-align: center"
            >
              <el-form
                :model="addruleForm"
                :rules="rulesadd"
                ref="addruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item
                  label="人员姓名"
                  prop="adduname"
                  style="margin: 20px; width: 80%; margin: 20px auto"
                >
                  <el-input
                    placeholder="请输入姓名"
                    v-model="addruleForm.adduname"
                    clearable
                    style="width: 300px; display: block"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item
                  label="人员手机号"
                  prop="addmobile"
                  style="margin: 20px; width: 80%; margin: 20px auto"
                >
                  <el-input
                    placeholder="请输入手机号"
                    v-model="addruleForm.addmobile"
                    clearable
                    style="width: 300px; display: block"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item
                  label="人员部门"
                  prop="usertype"
                  style="margin: 20px; width: 80%; margin: 20px auto"
                >
                  <el-select
                    v-model="addruleForm.usertype"
                    placeholder="请选择"
                    style="width: 300px; display: block"
                  >
                    <el-option label="宿管" value="1"></el-option>
                    <el-option label="总务" value="2"></el-option>
                    <el-option label="维修师傅" value="3"></el-option>
                    <el-option label="老师" value="4"></el-option>
                    <el-option label="学生" value="5"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="人员密码"
                  prop="addpwd"
                  style="margin: 20px; width: 80%; margin: 20px auto"
                >
                  <el-input
                    placeholder="请输入密码"
                    v-model="addruleForm.addpwd"
                    show-password
                    style="width: 300px; display: block"
                  >
                  </el-input>
                </el-form-item>
              </el-form>
              <!-- @click="submitForm('ruleForm')" -->
              <el-button
                type="primary"
                @click="submitadd('addruleForm')"
                style="padding: 10px 20px; margin: 5px"
                >确认添加</el-button
              >
              <el-button
                type="info"
                @click="resetForm('addruleForm')"
                style="padding: 10px 20px; margin: 5px"
                >重置已填</el-button
              >
            </el-drawer>
            <!-- 人员信息列表 -->
            <el-table
              :data="userlist"
              @selection-change="handleSelectionChange"
              ref="multipleTable"
              height="450"
              border
              style="width: 100%; margin: 20px auto"
            >
              <el-table-column label="全选" type="selection" width="55">
              </el-table-column>
              <el-table-column prop="id" label="ID" width="100">
              </el-table-column>
              <el-table-column prop="mobile" label="账号(手机号)" width="200">
              </el-table-column>
              <el-table-column prop="uname" label="姓名" width="180">
              </el-table-column>
              <el-table-column prop="part_name" label="部门" width="180">
              </el-table-column>

              <el-table-column prop="caozuo" label="操作">
                <template #default="scope">
                  <el-button
                    @click="xiugaiobtain(scope.row)"
                    type="primary"
                    style="margin-left: 16px; padding: 5px 10px"
                  >
                    <i class="el-icon-edit"></i>
                    编辑
                  </el-button>
                  <el-button
                    type="danger"
                    @click="open(scope.row)"
                    style="padding: 5px 10px"
                    ><i class="el-icon-delete"></i> 删除</el-button
                  >
                  <!-- 人员修改的drawer -->
                  <el-drawer
                    title="人员修改区"
                    :visible.sync="drawer"
                    :show-close="true"
                    style="text-align: center"
                  >
                    <el-form
                      :model="edutruleForm"
                      :rules="rulesedit"
                      ref="edutruleForm"
                      label-width="100px"
                      class="demo-ruleForm"
                    >
                      <el-form-item
                        label="人员姓名"
                        prop="unamesave"
                        style="margin: 20px; width: 80%; margin: 20px auto"
                      >
                        <el-input
                          placeholder="请输入姓名"
                          v-model="edutruleForm.unamesave"
                          clearable
                          style="width: 300px; display: block"
                        >
                        </el-input>
                      </el-form-item>
                      <el-form-item
                        label="人员手机号"
                        prop="umobilesave"
                        style="margin: 20px; width: 80%; margin: 20px auto"
                      >
                        <el-input
                          placeholder="请输入手机号"
                          v-model="edutruleForm.umobilesave"
                          clearable
                          style="width: 300px; display: block"
                        >
                        </el-input>
                      </el-form-item>
                      <el-form-item
                        label="人员部门"
                        prop="upartsave"
                        style="margin: 20px; width: 80%; margin: 20px auto"
                      >
                        <el-select
                          v-model="edutruleForm.upartsave"
                          placeholder="请选择"
                          style="width: 300px; display: block"
                        >
                          <el-option label="宿管" value="1"></el-option>
                          <el-option label="总务" value="2"></el-option>
                          <el-option label="维修师傅" value="3"></el-option>
                          <el-option label="老师" value="4"></el-option>
                          <el-option label="学生" value="5"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="人员密码"
                        prop="upwdsave"
                        style="margin: 20px; width: 80%; margin: 20px auto"
                      >
                        <el-input
                          placeholder="请输入密码"
                          v-model="edutruleForm.upwdsave"
                          show-password
                          style="width: 300px; display: block"
                        >
                        </el-input>
                      </el-form-item>
                    </el-form>

                    <el-button
                      type="success"
                      @click="submit('edutruleForm')"
                      style="padding: 10px 20px; margin: 10px 5px"
                      >确认修改</el-button
                    >
                    <el-button
                      type="info"
                      @click="reset('edutruleForm')"
                      style="padding: 10px 20px; margin: 10px 5px"
                      >重置已填</el-button
                    >
                  </el-drawer>
                </template>
              </el-table-column>
            </el-table>
            <!-- 批量操作 -->
            <div class="piliang" style="width: 95%">
              <el-button
                type="danger"
                @click="batchDelete"
                style="padding: 10px 15px"
                >批量删除</el-button
              >
              <el-button
                @click="toggleSelection()"
                type="primary"
                style="padding: 10px 15px"
                >取消选择</el-button
              >

              <!-- <el-button @click="clearSelection">取消批量</el-button> -->
            </div>
            <!-- 页码显示 -->
            <div class="block" style="max-width: 600px; margin: auto">
              <el-pagination
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalUsers"
                @size-change="handleChangeSize"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </div>
          </div>
        </template>
      </XPannel>
    </el-container>
  </div>
</template>

<script>
import http from "../api/http";
import * as XLSX from "xlsx";
import XPannel from "@/components/XPannel.vue";
import { mapState } from "vuex";
import BreadHeader from "@/components/BreadHeader.vue";

export default {
  components: {
    XPannel,
    BreadHeader
  },
  computed: {
    ...mapState(["name", "picture"]),
    userName() {
      return this.name;
    },
    userPicture() {
      return this.picture;
    },
  },
  data() {
    var validatePhone = (rule, value, callback) => {
      const pattern = /^1[3456789]\d{9}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!pattern.test(value)) {
        return callback(new Error("请输入正确格式的手机号"));
      } else {
        return callback();
      }
    };
    return {
      addruleForm: {
        adduname: "",
        addmobile: "",
        addpwd: "",
        usertype: null,
      },
      rulesadd: {
        adduname: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
        addmobile: [{ validator: validatePhone, trigger: "blur" }],
        addpwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur",
          },
        ],
        usertype: [
          { required: true, message: "请选择人员部门", trigger: "change" },
        ],
      },
      edutruleForm: {
        unamesave: "",
        umobilesave: "",
        upwdsave: "",
        upartsave: null,
      },
      rulesedit: {
        unamesave: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
        umobilesave: [{ validator: validatePhone, trigger: "blur" }],
        upwdsave: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur",
          },
        ],
        upartsave: [
          { required: true, message: "请选择人员部门", trigger: "change" },
        ],
      },
      userlist: [],
      drawer: false,
      draweradd: false,
      radio: 1,
      selected: [],
      xiugaiobtainuid: null,
      seacheruname: "",
      seachermobile: "",
      seacherpwd: "",
      seacherradio: 1,
      totalUsers: 0, //总数
      pageSize: 5, //每页条数
      pageNum: 1, //当前页码
      deluserid: null,
      searchvalue: "",
      excellist: [],
    };
  },
  methods: {
    // 导出EXCEL文件方法
    download() {
      const data = this.userlist;

      // 构造包含总标题和表头的二维数组
      const headers = ["用户id", "姓名", "手机号", "部门代号", "部门名称"]; // 表头
      const title = ["用户列表"]; // 总标题
      const worksheetData = [
        title,
        headers,
        ...data.map((item) => Object.values(item)),
      ]; // 数据

      // 将二维数组转换为工作表
      const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);

      // 设置总标题的样式
      const cellTitleRef = XLSX.utils.encode_cell({ c: 0, r: 0 }); // 获取总标题单元格的位置
      const cellTitle = worksheet[cellTitleRef];
      cellTitle.c = {
        alignment: {
          horizontal: "center", // 水平居中
          vertical: "center", // 垂直居中
        },
      };

      // 创建工作簿并添加工作表
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

      // 导出Excel文件
      XLSX.writeFile(workbook, "用户列表.xlsx");
    },
    // 搜索方法+接口
    searchusers() {
      http
        .get("/renyuan/search", {
          params: {
            uname: this.seacheruname.replace(/\s+/g, ""),
            account: this.seachermobile.replace(/\s+/g, ""),
            utype: this.searchvalue,
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((res) => {
          console.log(res);
          this.userlist = res.data;
          this.totalUsers = res.total;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    reset(formName) {
      this.$refs[formName].resetFields();
    },
    directclose() {
      this.$confirm(
        "检测到未保存的内容，是否在离开页面前保存修改？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "保存",
          cancelButtonText: "放弃修改",
        }
      )
        .then(() => {
          this.submit();
          this.$message({
            type: "info",
            message: "保存修改",
          });
        })
        .catch((action) => {
          this.$message({
            type: "info",
            message:
              action === "cancel" ? "放弃保存并离开页面" : "停留在当前页面",
          });
          if (action === "cancel") {
            this.drawer = false;
          }
        });
    },
    directcloseadd() {
      this.$confirm(
        "检测到未保存的内容，是否在离开页面前保存添加？",
        "确认信息",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "保存",
          cancelButtonText: "放弃添加",
        }
      )
        .then(() => {
          this.adduserfn();
          this.$message({
            type: "info",
            message: "保存添加",
          });
        })
        .catch((action) => {
          // this.draweradd = false
          this.$message({
            type: "info",
            message:
              action === "cancel" ? "放弃添加并离开页面" : "停留在当前页面",
          });
          if (action === "cancel") {
            this.draweradd = false;
            this.resetadd();
          }
        });
    },
    handleChangeSize(data) {
      this.pageSize = data;
      const isSeacherunameDefault = this.seacheruname === "";
      const isSeachermobileDefault = this.seachermobile === "";
      const isSeacherpwdDefault = this.searchvalue === "";

      const isAllDefaults =
        isSeacherunameDefault && isSeachermobileDefault && isSeacherpwdDefault;

      if (isAllDefaults) {
        // 如果所有字段都是初始值，则调用userlistfn
        this.userlistfn();
      } else {
        // 否则，调用searchusers
        this.searchusers();
      }
    },
    handleCurrentChange(data) {
      this.pageNum = data;
      const isSeacherunameDefault = this.seacheruname === "";
      const isSeachermobileDefault = this.seachermobile === "";
      const isSeacherpwdDefault = this.searchvalue === "";

      const isAllDefaults =
        isSeacherunameDefault && isSeachermobileDefault && isSeacherpwdDefault;

      if (isAllDefaults) {
        // 如果所有字段都是初始值，则调用userlistfn
        this.userlistfn();
      } else {
        // 否则，调用searchusers
        this.searchusers();
      }
    },
    changeRadio(data) {
      this.upartsave = data;
    },
    // 删除按钮的方法
    open(row) {
      this.$confirm("此操作将永久删除该人员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(1, row);
          // this.deluserid = this.userlist[row].id
          this.deluserid = row.id;
          this.deleteuserfn();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.userlistfn();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除方法+接口
    deleteuserfn() {
      http
        .get("/renyuan/delete/" + this.deluserid)
        .then((response) => {
          console.log(response);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 列表方法+接口
    userlistfn() {
      http
        .get("/renyuan/list", {
          params: {
            page: this.pageNum,
            page_size: this.pageSize,
          },
        })
        .then((response) => {
          console.log(response);
          console.log(response.data);
          // this.userlist.push(response.data)
          this.userlist = response.data.list;
          console.log(this.userlist);
          this.totalUsers = response.data.totalNum;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    handleSelectionChange(val) {
      this.selected = val;
      console.log(this.selected);
    },
    // 人员删除按钮
    batchDelete() {
      if (this.selected.length === 0) {
        this.$message({
          message: "请先选择要删除的项",
          type: "warning",
        });
        return;
      }
      this.$confirm("此操作将永久删除选中的人员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 批量删除---代办--ok
          this.selected.forEach((item) => {
            // const index = this.userlist.indexOf(item);
            let deluserids = [];
            deluserids.push(item.id);
            let deluseridsting = JSON.stringify(deluserids);
            http
              .get("/renyuan/deletes/" + deluseridsting)
              .then((response) => {
                console.log(response);
              })
              .catch((error) => {
                console.log(error);
              });
            this.userlistfn();
            // this.userlist.splice(index, 1);
          });
          this.selected = []; // 清空选中的项
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // clearSelection() {
    //     this.selected = [];
    // },
    // 人员修改--获取数据
    xiugaiobtain(row) {
      this.drawer = true;
      console.log(row.id);
      let editid = row.id;
      http
        .get("/renyuan/edit/" + editid)
        .then((response) => {
          console.log(response);
          this.xiugaiobtainuid = response.data[0].id;
          this.edutruleForm.unamesave = response.data[0].uname;
          this.edutruleForm.umobilesave = response.data[0].account;
          this.edutruleForm.upartsave = response.data[0].pname;
          this.edutruleForm.upwdsave = response.data[0].pwd;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 人员修改--保存数据
    submit(edutruleForm) {
      this.$refs[edutruleForm].validate((valid) => {
        if (valid) {
          this.$message({
            message: "恭喜你，人员修改成功！",
            type: "success",
          });
          http
            .post("/renyuan/save_edit/" + this.xiugaiobtainuid, {
              uname: this.edutruleForm.unamesave,
              part: this.edutruleForm.upartsave,
              mobile: this.edutruleForm.umobilesave,
              pwd: this.edutruleForm.upwdsave,
            })
            .then((response) => {
              console.log(response);
              this.userlistfn();
              this.drawer = false;
            })
            .catch((error) => {
              console.log(error);
            });
          this.drawer = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加人员按钮
    adduser() {
      this.draweradd = true;
    },
    // 添加人员接口
    adduserfn() {
      http
        .post("/renyuan/add", {
          uname: this.addruleForm.adduname,
          part: this.addruleForm.usertype,
          mobile: this.addruleForm.addmobile,
          pwd: this.addruleForm.addpwd,
        })
        .then((response) => {
          if (response.code == 0) {
            this.$message({
              message: response.msg,
              type: "success",
            });
            
          } else {
            this.$message({
              message: response.msg,
              type: "warning",
            });
          }
          this.userlistfn();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 添加人员重置方法
    resetadd() {
      this.addruleForm.adduname = "";
      this.addruleForm.usertype = 1;
      this.addruleForm.addmobile = "";
      this.addruleForm.addpwd = "";
    },
    // 添加人员提交按钮
    submitadd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.adduserfn();
          this.resetadd();
          this.draweradd = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    partvalue() {
      if (this.userlist.part == 1) {
        this.userlist.part == "宿管";
      } else if (this.userlist.part == 2) {
        this.userlist.part == "总务";
      } else if (this.userlist.part == 3) {
        this.userlist.part == "维修师傅";
      }
    },
  },

  created() {
    this.userlistfn();
    this.partvalue();
  },
};
</script>

<style scoped lang="less">
// .el-container{
//     .el-header{
//         color: #ffffff;
//         display: flex;
//         p{
//             display: flex;
//             width: 220px;
//             margin: 20px 40px;
//         }
//         button{
//             height: 40px;
//             padding: 10px 20px;
//             margin-top: 10px;
//         }
//     }
// }
.el-row {
  // margin-top:20px;
  // margin-bottom: 20px;
  // margin: 10px;
  color: #ffffff;
  &:last-child {
    margin-bottom: 0;
  }
  &:nth-child(2) {
    margin: 15px;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
.block {
  background: #ffffff;
  padding: 20px;
}

.el-main {
  background: #ffffff;
}

/deep/.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
/deep/.el-icon-arrow-down {
  font-size: 12px;
}
</style>